package com.hy.mechanicalarm.ui.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.hy.mechanicalarm.R;
import com.hy.mechanicalarm.baseapp.BaseFragment;
import com.hy.mechanicalarm.constant.Constants;
import com.hy.mechanicalarm.ui.activity.SettingActivity;
import com.hy.mechanicalarm.ui.service.SocketService;
import com.hy.mechanicalarm.utils.CommonUtil;
import com.hy.mechanicalarm.utils.SPUtil;

import butterknife.BindView;

/**
 *  2018/8/7 15:24
 *  hanyin
 *  hanyinit@163.com
 */
public class QTSettingFragment extends BaseFragment implements View.OnClickListener{

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";


    private String mParam1;
    private String mParam2;


    @BindView(R.id.btnSave)
    Button btnSave ;
    @BindView(R.id.compound_min)
    EditText compound_min;
    @BindView(R.id.compound_max)
    EditText compound_max;
    @BindView(R.id.compound_calibration)
    EditText compound_calibration;
    @BindView(R.id.temperature_min)
    EditText temperature_min;
    @BindView(R.id.temperature_max)
    EditText temperature_max;
    @BindView(R.id.temperature_calibration)
    EditText temperature_calibration;
    @BindView(R.id.quiet_times)
    EditText quiet_times;
    @BindView(R.id.halt_times)
    EditText halt_times;
    @BindView(R.id.measure_times)
    EditText measure_times;
    private String  timeOrder= "AA55001103xy000dCC33";
    private String  timeOrder2= "001103xy";
    private LocalBroadcastManager mLocalBroadcastManager;
    private MessageBackReciver mReciver;
    private IntentFilter mIntentFilter;
    SPUtil spUtil ;
    public QTSettingFragment() {

    }
    class MessageBackReciver extends BroadcastReceiver {

        public MessageBackReciver() {
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(SocketService.HEART_BEAT_ACTION)) {
            } else {
                String message = intent.getStringExtra("message");
                if("03".equals(message.substring(8,10))){
                    //设置时间参数
                    String data = message.substring(14,18);
                    if("0000".equals(data)){
                        CommonUtil.showToast("设置时间参数");
                    }
                }
            }
        }
    }

    public static QTSettingFragment newInstance(String param1, String param2) {
        QTSettingFragment fragment = new QTSettingFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void initView(View rootView) {
        super.initView(rootView);
        mLocalBroadcastManager = LocalBroadcastManager.getInstance(getActivity());
        mReciver = new MessageBackReciver();
        mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(SocketService.HEART_BEAT_ACTION);
        mIntentFilter.addAction(SocketService.MESSAGE_ACTION);
        mLocalBroadcastManager.registerReceiver(mReciver, mIntentFilter);
    }

    @Override
    public void initData() {
        super.initData();
        spUtil = new SPUtil(getActivity());
        compound_min.setText(spUtil.getInt(Constants.COMPOUND_MIN,0)+"");
        compound_max.setText(spUtil.getInt(Constants.COMPOUND_MAX,25)+"");
        compound_calibration.setText(spUtil.getInt(Constants.COMPOUND_CALIBRATION,5)+"");
        temperature_min.setText(spUtil.getInt(Constants.TEMPERATURE_MIN,0)+"");
        temperature_max.setText(spUtil.getInt(Constants.TEMPERATURE_MAX,200)+"");
        temperature_calibration.setText(spUtil.getInt(Constants.TEMPERATURE_CALIBRATION,5)+"");
        quiet_times.setText(spUtil.getInt(Constants.QUIET_TIMES,10)+"");
        halt_times.setText(spUtil.getInt(Constants.HALT_TIMES,60)+"");
        measure_times.setText(spUtil.getInt(Constants.MEASURE_TIMES,30)+"");
    }

    @Override
    public void initListener() {
        super.initListener();
        btnSave.setOnClickListener(this);
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_qtsetting;
    }

    @Override
    protected void loadData() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btnSave:
                String compound_minStr = compound_min.getText().toString();
                String compound_maxStr = compound_max.getText().toString();
                String compound_calibrationStr = compound_calibration.getText().toString();
                String temperature_mixStr = temperature_min.getText().toString();
                String temperature_maxStr = temperature_max.getText().toString();
                String temperature_calibrationStr = temperature_calibration.getText().toString();
                String quiet_timesStr = quiet_times.getText().toString();
                String halt_timesStr = halt_times.getText().toString();
                String measure_timesStr = measure_times.getText().toString();
                if(TextUtils.isEmpty(compound_minStr)){
                    CommonUtil.showToast("极性化合物最小值不能为空");
                    return;
                }
                if(TextUtils.isEmpty(compound_maxStr)){
                    CommonUtil.showToast("极性化合物最大值不能为空");
                    return;
                }
                if(TextUtils.isEmpty(compound_calibrationStr)){
                    CommonUtil.showToast("极性化合物校准不能为空");
                    return;
                }
                if(TextUtils.isEmpty(temperature_mixStr)){
                    CommonUtil.showToast("温度最小值不能为空");
                    return;
                }
                if(TextUtils.isEmpty(temperature_maxStr)){
                    CommonUtil.showToast("温度最大值不能为空");
                    return;
                }
                if(TextUtils.isEmpty(temperature_calibrationStr)){
                    CommonUtil.showToast("温度校准不能为空");
                    return;
                }
                if(TextUtils.isEmpty(quiet_timesStr)){
                    CommonUtil.showToast("静音时间不能为空");
                    return;
                }
                if(TextUtils.isEmpty(halt_timesStr)){
                    CommonUtil.showToast("停机时间不能为空");
                    return;
                }
                if(TextUtils.isEmpty(measure_timesStr)){
                    CommonUtil.showToast("测量不能为空");
                    return;
                }

                spUtil.putInt(Constants.COMPOUND_MIN,Integer.valueOf(compound_minStr));
                spUtil.putInt(Constants.COMPOUND_MAX,Integer.valueOf(compound_maxStr));
                spUtil.putInt(Constants.COMPOUND_CALIBRATION,Integer.valueOf(compound_calibrationStr));
                spUtil.putInt(Constants.TEMPERATURE_MIN,Integer.valueOf(temperature_mixStr));
                spUtil.putInt(Constants.TEMPERATURE_MAX,Integer.valueOf(temperature_maxStr));
                spUtil.putInt(Constants.TEMPERATURE_CALIBRATION,Integer.valueOf(temperature_calibrationStr));
                spUtil.putInt(Constants.QUIET_TIMES,Integer.valueOf(quiet_timesStr));
                spUtil.putInt(Constants.HALT_TIMES,Integer.valueOf(halt_timesStr));
                spUtil.putInt(Constants.MEASURE_TIMES,Integer.valueOf(measure_timesStr));
                sendSaveOrder(halt_timesStr,measure_timesStr);
                //getActivity().finish();
                break;
        }
    }

    /**
     * 设置时间参数
     * @param halt_timesStr
     * @param measure_timesStr
     */
    private void sendSaveOrder(String halt_timesStr, String measure_timesStr) {
        String haltTimes = Integer.toHexString(Integer.valueOf(halt_timesStr));
        String measureTimes = Integer.toHexString(Integer.valueOf(measure_timesStr));
//        timeOrder =  timeOrder.replace("x",polishingParame(haltTimes));
//        timeOrder =  timeOrder.replace("y",polishingParame(measureTimes));
//        ((SettingActivity)getActivity()).socketService.sendMsg(timeOrder);
        String time =  timeOrder2.replace("x",polishingParame(haltTimes))
                .replace("y",polishingParame(measureTimes));
        time += makeChecksum(time);
        ((SettingActivity)getActivity()).socketService.sendMsg("AA55"+time+"CC33");
    }
    /**
     * 补齐参数
     * @param parame
     * @return
     */
    public String  polishingParame(String parame){
        StringBuffer sb = new StringBuffer();

        if(parame.length()==1){
            sb.append("0000000");
        }else if(parame.length()==2){
            sb.append("000000");
        }else if(parame.length()==3){
            sb.append("00000");
        }else if(parame.length()==4){
            sb.append("0000");
        }else if(parame.length()==5){
            sb.append("000");
        }else if(parame.length()==6){
            sb.append("00");
        }else if(parame.length()==7){
            sb.append("0");
        }
        sb.append(parame);
        return sb.toString();
    }

    public String makeChecksum(String data) {
        if (data == null || data.equals("")) {
            return "";
        }
        int total = 0;
        int len = data.length();
        int num = 0;
        while (num < len) {
            String s = data.substring(num, num + 2);
            total += Integer.parseInt(s, 16);
            num = num + 2;
        }
        /**
         * 用256求余最大是255，即16进制的FF
         */
        int mod = total % 256;
        String hex = Integer.toHexString(mod);
        len = hex.length();
        // 如果不够校验位的长度，补0,这里用的是两位校验
        if (len == 2) {
            hex = "00" + hex;
        }else if (len == 1) {
            hex = "000" + hex;
        }else if (len == 3) {
            hex = "0" + hex;
        }
        return hex;
    }
}